package main

import (
	"bufio"
	"fmt"
	"log"
	"net"
)

func main() {
	listen, err := net.Listen("tcp", "127.0.0.1:1888")
	if err != nil {
		log.Fatal(err)
		return
	}
	defer listen.Close()

	for {
		conn, err := listen.Accept()
		if err != nil {
			log.Fatal(err)
			continue
		}
		fmt.Printf("连接成功，来自%v\n", conn.RemoteAddr().String())
		go readWrite(conn)
	}
}

func readWrite(conn net.Conn) {
	defer conn.Close()
	reader := bufio.NewReader(conn)
	for {
		tmp := make([]byte, 1024)
		read, err := reader.Read(tmp)
		if err != nil {
			log.Fatal(err)
			break
		}
		loadStr := string(tmp[:read])
		fmt.Println("读取到数据:", loadStr)
		conn.Write([]byte("收到了数据:" + loadStr))
	}
}
